# encoding: utf-8
from flask import render_template, flash, redirect, url_for
from . import category
from flask_login import login_required
from ..forms import CategoryForm, LoginForm
from ..models import Category

@category.route("/list", methods=["GET", "POST"])
@login_required
def list():
    form = CategoryForm()
    if form.validate_on_submit():
        name = form.name.data

        # 判断分类名称是否存在
        is_name_existed = Category.is_name_existed(name)
        # 如果存在则直接返回
        if is_name_existed:
            flash("此分类已存在")
        else:
            # 保存
            category = Category(name)
            category.add()

            return redirect(url_for("category.list"))
    else:
        error = form.errors.get("name") and form.errors.get("name")[0]
        flash(error)

    # 获取分类列表
    category_list = Category.queryAll()
    return render_template("category_list.html", form=form, list=category_list)

@category.route("/delete/<int:id>")
@login_required
def delete(id):
    # 按照id删除分类
    Category.deleteById(id)
    # 返回到列表页面
    return redirect(url_for("category.list"))